import { SysMenuTree } from '@/interface/user'
import { defineStore } from 'pinia'
import router from '@/router/index'
import { HeadTag } from '@/interface/menu'
import { useGlobalStore } from './globalStore'

export const useMenuStore = defineStore('menu', {
  state: () => ({
    collapsed: document.body.clientWidth <= 640 ,//移动端隐藏
    selectedKeys: ["/index"],
    openKeys: [document.body.clientWidth <= 640 ? "" : "/sys"],//移动端不弹出选项
    preOpenKeys: [""],
    isLoading: false,
    menuList: [] as SysMenuTree[],
    fixedMenuList: [] as SysMenuTree[],
    dynamicTagList: [
      {
        key: '/index',
        title: '首页',
        enableClose: false,
        isActive: true,
      },
    ] as HeadTag[],
    pathToName: {} as Record<string, any>,
  }),
  getters: {
  },
  actions: {
    setMenuList(menuList: SysMenuTree[]) {
      this.menuList = menuList
    },
    setFixedMenuList(fixedMenuList: SysMenuTree[]) {
      this.fixedMenuList = fixedMenuList
    },
    resetDynamicTag() {
      this.dynamicTagList.map((tag: HeadTag) => {
        tag.isActive = false
        return tag
      })
    },
    addDynamicTag(currTag: HeadTag) {
      let findObj = this.dynamicTagList.find((item: HeadTag) => {
        return item.key == currTag.key
      })
      if (!findObj) {
        this.resetDynamicTag()
        this.dynamicTagList.push(Object.assign({}, currTag))
      }
    },
    toggleDynamicTag(key: string | number) {
      this.resetDynamicTag()
      const globalStore = useGlobalStore()
      this.dynamicTagList.map((item: HeadTag) => {
        if (item.key == key) {
          item.isActive = true
          if (globalStore.dyTitleMode === '1') {
            document.title = '管理后台-' + item.title
          }
        }
        return item
      })
    },
    saveDynamicTag2Local() {
      const preDyTag: HeadTag[] = JSON.parse(localStorage.getItem("dynamicTags") || "[]");
      let dyTag: HeadTag[] = [...preDyTag, ...this.dynamicTagList]
      let set = new Set()
      //去重
      dyTag = dyTag.filter(item => {
        let back = !set.has(item.key)
        set.add(item.key)
        item.isActive = false
        return back
      })
      localStorage.setItem("dynamicTags", JSON.stringify(dyTag));
    },
    deleteDynamicTag(key: string | number) {
      if (this.selectedKeys[0] == key) {
        //当前选中的标签被删除
        this.selectedKeys = ['/index']
        router.push('/index')
        this.dynamicTagList[0].isActive = true
      }
      this.dynamicTagList = this.dynamicTagList.filter((item: HeadTag) => {
        return item.key != key
      })
      localStorage.setItem('dynamicTags', JSON.stringify(this.dynamicTagList))
    },
    //根据路径构造面包屑名称
    async ceateBreadcrumbName(path: string, _refresh = false) {
      let backPath = ''
      let pathMap: Record<string, string> = {}
      /**
       * 
       * @param menu 当前菜单
       * @param p 菜单对应的路径
       * @returns 
       */
      const dfs = (menu: SysMenuTree, p: string) => {
        if (path.includes(menu.path as string)) {
          path = path.replace(menu.path as string, '')
          if (path.startsWith('/')) {
            //路径形式例如 /index/user 数据库形式/index  user第二次的/需要清除
            path = path.substring(1)
          }
          backPath += menu.name + '#' //#分隔符
          pathMap[menu.name as string] = p + (menu.path?.startsWith('/') ? '' : '/') + menu.path //生成路径
          if (path == '') {
            return true
          }
        }
        if (menu.children) {
          for (let children of menu.children) {
            if (dfs(children, p + menu.path as string)) {
              return true
            }
          }
        }
        return false
      }
      for (let menu of this.menuList) {
        backPath = ''
        if (dfs(menu, '')) {
          return {
            backPath: backPath.substring(0, backPath.length - 1),
            pathMap
          }
        }
      }
      return {}
    }
  },
})